<template>
  <div class="el-form-item">
    {{ label }}
    <input v-model="localValue" type="text" />
    <span v-show="error" class="error">{{ error }}</span>
  </div>
</template>
<script lang="ts">
export default {
  name: "ElFormItem",
};
</script>
<script setup lang="ts">
import Schema from "async-validator";
import { computed, withDefaults, inject, onMounted, ref, watchEffect } from "vue";
interface Props {
  label?: string;
  prop?: string;
}
const props = withDefaults(defineProps<Props>(), {
  label: "",
  prop: "",
});
const error = ref("");
const formEmitter = inject("formEmitter");
const formData = inject("formData");
let propValue = formData.model[props.prop];
let localValue = ref(propValue || "");

onMounted(() => {
  formEmitter.emit("itemMounted", validate);
});
const rules = formData.rules[props.prop];

let triggerTypes = "";
if (rules) {
  if (Array.isArray(rules)) {
    triggerTypes = rules.map((rule) => rule.trigger && rule.trigger).join(' ');
  } else {
    triggerTypes = rules.trigger;
  }
}
function validate() {
  if (!rules) return
  if (formData?.rules === undefined) {
    return Promise.resolve({ result: true });
  }
  let sc = {}
  sc[props.prop] =localValue.value
  let descriptor = {}
  descriptor[props.prop] = rules
  debugger
  const schema = new Schema(descriptor);
  return schema.validate(sc, (errors, fields) => {
    if (errors) {
      error.value = errors[0].message || "校验错误";
    } else {
      error.value = "";
    }
  });
}
</script>
<style lang="scss">
@import "../../styles/mixin";
@include b(form-item) {
  margin-bottom: 22px;
  label {
    line-height: 1.2;
    margin-bottom: 5px;
    display: inline-block;
  }
  & .el-form-item {
    margin-bottom: 0;
  }
}
.error {
  color: red;
}
</style>
